package com.cardbaobao.cardbabyclient.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;

import java.util.List;

/**
 * DropDownMenu
 * Created by zad
 * 2016/7/21 9:06
 */

public class DropDownMenuView extends LinearLayout implements Animation.AnimationListener {
    /**
     * 顶部标题栏布局
     */
    private LinearLayout mTabMenuView;
    /**
     * 底部内容包裹区域,包裹内容包括mPopMenuView mBottomView
     */
    private FrameLayout mContainerView;
    /**
     * 底部弹出View的父布局，用于装载外部传过来的布局
     */
    private FrameLayout mPopMenuParentView;
    /**
     * 底部半透明View
     */
    private View mBottomView;
    /**
     * 背景色
     */
    private int menuBackgroundColor = Color.parseColor("#FFFFFF");
    /**
     * 字体大小
     */
    private int menuTextSize = 14;
    /**
     * 文本未被选中的颜色
     */
    private int menuTextUnSelectedColor = Color.parseColor("#666666");
    /**
     * 文本被选中的颜色
     */
    private int menuTextSelectedColor = Color.parseColor("#007AFF");
    /**
     * 标题未被选中的图标源地址
     */
    private int menuUnSelectedIcon;

    private Drawable mMenuUnSelectedDrawable;
    /**
     * 标题被选中的图标地址
     */
    private int menuSelectedIcon;

    private Drawable mMenuSelectedDrawable;
    /**
     * 标题分割线颜色（暂时没使用到）
     */
    private int menuDividerColor = Color.parseColor("#DDDDDD");
    /**
     * 标题底部下划线颜色
     */
    private int menuUnderLineColor = Color.parseColor("#DDDDDD");
    /**
     * 菜单显示时的底部半透明颜色
     */
    private int menuBottomColor = Color.parseColor("#75000000");
    /**
     * 标题文字内边距
     */
    private int menuTextLeftPadding,menuTextTopPadding,menuTextRightPadding,menuTextBottomPadding;


    public DropDownMenuView(Context context) {
        this(context, null);
    }

    public DropDownMenuView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DropDownMenuView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(VERTICAL);//设置View垂直方式加载布局
        initAttribute(context,attrs,defStyleAttr);
        //初始化顶部菜单栏mTabView
        mTabMenuView = new LinearLayout(context);
        mTabMenuView.setOrientation(HORIZONTAL);
        mTabMenuView.setBackgroundColor(menuBackgroundColor);
        mTabMenuView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        addView(mTabMenuView, 0);

        //初始化顶部菜单栏下方的横线
        View mUnderLine = new View(context);
        mUnderLine.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dpToPx(1.0f)));
        mUnderLine.setBackgroundColor(menuUnderLineColor);
        addView(mUnderLine, 1);

        //初始化底部内容包裹区域
        mContainerView = new FrameLayout(context);
        mContainerView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        addView(mContainerView, 2);

    }

    /**
     * 初始化属性
     */
    private void initAttribute(Context context, AttributeSet attrs, int defStyleAttr){
        TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.DropDownMenu);
        menuBackgroundColor = a.getColor(R.styleable.DropDownMenu_menuBackgroundColor, menuBackgroundColor);
        menuTextSize = a.getInt(R.styleable.DropDownMenu_menuTextSize, menuTextSize);
        menuTextUnSelectedColor = a.getColor(R.styleable.DropDownMenu_menuTextUnSelectedColor, menuTextUnSelectedColor);
        menuTextSelectedColor = a.getColor(R.styleable.DropDownMenu_menuTextSelectedColor, menuTextSelectedColor);
        menuUnSelectedIcon = a.getResourceId(R.styleable.DropDownMenu_menuUnSelectedIcon, -1);
        menuSelectedIcon = a.getResourceId(R.styleable.DropDownMenu_menuSelectedIcon, -1);
        menuDividerColor = a.getColor(R.styleable.DropDownMenu_menuDividerColor, menuDividerColor);
        menuUnderLineColor = a.getColor(R.styleable.DropDownMenu_menuUnderLineColor,menuUnderLineColor);
        menuBottomColor = a.getColor(R.styleable.DropDownMenu_menuBottomColor,menuBottomColor);
        menuTextLeftPadding = (int) a.getDimension(R.styleable.DropDownMenu_menuTextLeftPadding,menuTextLeftPadding);
        menuTextTopPadding = (int) a.getDimension(R.styleable.DropDownMenu_menuTextTopPadding,menuTextTopPadding);
        menuTextRightPadding = (int) a.getDimension(R.styleable.DropDownMenu_menuTextRightPadding,menuTextRightPadding);
        menuTextBottomPadding = (int) a.getDimension(R.styleable.DropDownMenu_menuTextBottomPadding,menuTextBottomPadding);

        mMenuUnSelectedDrawable = ContextCompat.getDrawable(context,menuUnSelectedIcon);
        mMenuSelectedDrawable = ContextCompat.getDrawable(context,menuSelectedIcon);
        a.recycle();
    }

    /**
     * @param mTabTexts    标题集合
     * @param mPopViews    点击标题弹出的View集合
     * @param mContentView 底部内容显示区域
     */
    public void setDropDownMenu(List<String> mTabTexts, List<View> mPopViews, View mContentView) {
        if (mTabTexts == null || mPopViews == null || mContentView == null || mTabTexts.size() != mPopViews.size()) {
            //判断标题内容和要显示的布局个数是否相同
            return;
        }
        for (int i = 0, l = mTabTexts.size(); i < l; i++) {
            addTabView(mTabTexts, i);//循环添加标题
        }
        //将内容区域放置于容器底部
        mContainerView.addView(mContentView, 0);
        //添加半透明布局
        mBottomView = new View(getContext());
        mBottomView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mBottomView.setBackgroundColor(menuBottomColor);
        mBottomView.setVisibility(View.GONE);
        mContainerView.addView(mBottomView, 1);
        mBottomView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                closeDropMenu();
            }
        });
        //初始化弹出PopMenu内容父布局
        mPopMenuParentView = new FrameLayout(getContext());
        mPopMenuParentView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mPopMenuParentView.setVisibility(View.GONE);
        mContainerView.addView(mPopMenuParentView, 2);
        //将弹出子菜单添加到父布局中
        for (int i = 0, l = mPopViews.size(); i < l; i++) {
            View view = mPopViews.get(i);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            view.setVisibility(View.GONE);
            mPopMenuParentView.addView(view, i);
        }
    }

    /**
     * 　将标题内容动态添加到标题
     *
     * @param mTabTexts 标题集合
     * @param index     下标
     */
    private void addTabView(List<String> mTabTexts, final int index) {
        //用于包裹TextView，如果不加这一层，TextView里的文本和图标间距很宽
        final LinearLayout tabParent = new LinearLayout(getContext());
        tabParent.setGravity(Gravity.CENTER);
        //等分标题宽度
        tabParent.setLayoutParams(new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT,1.0f));
        final TextView tabView = new TextView(getContext());
        tabView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        tabView.setSingleLine();//单行
        tabView.setEllipsize(TextUtils.TruncateAt.END);//末尾 ...标识
        tabView.setPadding(menuTextLeftPadding,menuTextTopPadding,menuTextRightPadding,menuTextBottomPadding);
        tabView.setTextColor(menuTextUnSelectedColor);
        tabView.setText(mTabTexts.get(index));
        tabView.setTextSize(menuTextSize);
        tabView.setCompoundDrawablesWithIntrinsicBounds(null, null,mMenuUnSelectedDrawable, null);
        tabView.setTag(false);//（用于标记当前标题是否被选中）
        //标题单击事件
        tabView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switchMenu(index);
                if(onDropMenuClickListener != null){
                    onDropMenuClickListener.onDropMenuClick(index);
                }
            }
        });
        tabParent.addView(tabView);
        mTabMenuView.addView(tabParent);
    }

    /**
     * 当前选中菜单位置
     */
    private int mCurrentTabPos = -1;
    /**
     * 上一次选中菜单位置
     */
    private int mLastTabPos = -1;
    /**
     * 当前选中的tabView
     */
    private TextView mSelectTabView;
    /**
     * 当前Menu是否显示
     */
    public boolean isShowing = false;
    /**
     * 是否滚动下拉显示
     */
    private boolean isCrollDownShow = false;

    /**
     * 菜单切换
     *
     * @param index 被单击的下标
     */
    private void switchMenu(int index) {
        mLastTabPos = mCurrentTabPos;
        mCurrentTabPos = index;
        swithPopMenu();
    }

    /**
     * 切换PopMenu
     */
    private void swithPopMenu() {
        isShowing = true;
        if (mCurrentTabPos != -1) {
            //设置被选中的标题
            LinearLayout mTabParent = (LinearLayout) mTabMenuView.getChildAt(mCurrentTabPos);
            mSelectTabView = (TextView) mTabParent.getChildAt(0);//标题
            View popView = mPopMenuParentView.getChildAt(mCurrentTabPos);//弹出布局
            if (mSelectTabView != null) {
                boolean isSelected = (boolean) mSelectTabView.getTag();
                if (isSelected) {//close
                    //已经被选中，还原选中
                    hideMenu();
                } else {//show
                    //没有被选中，设置选中
                    mSelectTabView.setTextColor(menuTextSelectedColor);
                    mSelectTabView.setCompoundDrawablesWithIntrinsicBounds(null, null, mMenuSelectedDrawable, null);
                    mSelectTabView.setTag(true);
                    if (popView != null && popView.getVisibility() == View.GONE) {
                        popView.setVisibility(VISIBLE);
                    }
                    showMenu();
                }
            }
        }
        if (mLastTabPos != -1 && mLastTabPos != mCurrentTabPos) {
            //还原上一个标题颜色
            LinearLayout mTabParent = (LinearLayout) mTabMenuView.getChildAt(mLastTabPos);
            TextView tabView = (TextView) mTabParent.getChildAt(0);//标题
            View popView = mPopMenuParentView.getChildAt(mLastTabPos);//弹出布局
            if (tabView != null) {
                tabView.setTextColor(menuTextUnSelectedColor);
                tabView.setCompoundDrawablesWithIntrinsicBounds(null, null, mMenuUnSelectedDrawable, null);
                tabView.setTag(false);
            }
            //隐藏上一个MenuView
            if (popView != null && popView.getVisibility() == View.VISIBLE) {
                popView.setVisibility(GONE);
            }
        }
    }

    /**
     * 关闭菜单
     */
    public void closeDropMenu(){
        isCrollDownShow = true;
        hideMenu();
    }

    /**
     * 隐藏菜单
     */
    private void hideMenu() {
        isShowing = false;
        mSelectTabView.setTextColor(menuTextUnSelectedColor);
        mSelectTabView.setCompoundDrawablesWithIntrinsicBounds(null, null, mMenuUnSelectedDrawable, null);
        mSelectTabView.setTag(false);//设置标记未被选中
        if (mPopMenuParentView.getVisibility() == View.VISIBLE)
            mPopMenuParentView.setVisibility(View.GONE);
        if (mBottomView.getVisibility() == View.VISIBLE)
            mBottomView.setVisibility(GONE);
        Animation anim_menu_out = AnimationUtils.loadAnimation(getContext(), R.anim.drop_menu_out);
        anim_menu_out.setAnimationListener(this);//监听动画开始结束
        mPopMenuParentView.setAnimation(anim_menu_out);
        mBottomView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.drop_bottom_out));
    }

    /**
     * 显示菜单
     */
    private void showMenu() {
        if (mPopMenuParentView.getVisibility() == View.GONE)
            mPopMenuParentView.setVisibility(View.VISIBLE);
        if (mBottomView.getVisibility() == View.GONE)
            mBottomView.setVisibility(VISIBLE);
        if (mCurrentTabPos == mLastTabPos || mLastTabPos == -1 || isCrollDownShow) {
            Animation anim_menu_in = AnimationUtils.loadAnimation(getContext(), R.anim.drop_menu_in);
            anim_menu_in.setAnimationListener(this);//监听动画开始结束
            mPopMenuParentView.setAnimation(anim_menu_in);
            mBottomView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.drop_bottom_in));
        }
        isCrollDownShow = false;
    }



    /**
     * 设置标题文本
     * @param text
     */
    public void setTabMenuText(String text){
        if(mCurrentTabPos != -1){
            LinearLayout mTabParent = (LinearLayout) mTabMenuView.getChildAt(mCurrentTabPos);
            TextView tabView = (TextView) mTabParent.getChildAt(0);//标题
            if(tabView != null){
                tabView.setText(text);
            }
        }
    }

    private int dpToPx(float value) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm) + 0.5);
    }

    /**
     * 动画开始
     * @param animation
     */
    @Override
    public void onAnimationStart(Animation animation) {
        if(onDropMenuClickListener != null){
            onDropMenuClickListener.onDropMenuClick(mCurrentTabPos);
        }
    }

    /**
     * 动画结束
     * @param animation
     */
    @Override
    public void onAnimationEnd(Animation animation) {
        if(onDropMenuClickListener != null){
            onDropMenuClickListener.onDropMenuAnimEnd();
        }
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    private OnDropMenuListener onDropMenuClickListener;

    public void setOnDropMenuListener(OnDropMenuListener onDropMenuClickListener){
        this.onDropMenuClickListener = onDropMenuClickListener;
    }

    /**
     * 下拉菜单单击回调
     */
    public interface OnDropMenuListener{
        /**
         * 下拉菜单单击回调
         * @param index 被单击的菜单位置
         */
        void onDropMenuClick(int index);
        /**
         * 动画结束
         */
        void onDropMenuAnimEnd();
    }

}
